from __future__ import with_statement

import pyflag.FlagFramework as FlagFramework
import pyflag.conf
config=pyflag.conf.ConfObject()
import pyflag.FileSystem as FileSystem
import pyflag.Reports as Reports
import pyflag.DB as DB
from pyflag.Scanner import *
import pyflag.Scanner as Scanner
from pyflag.ColumnTypes import StringType, InodeIDType, FilenameType, IntegerType, TimestampType, LongStringType
import pyflag.Reports as Reports
import os.path

import sys
from struct import unpack_from, error as StructError
from math import ceil

def iterate_tlen_chats(filename):
    with open(filename) as f:
        return get_lines(f.read())

def get_lines(raw):
    offset = 0
    while offset < len(raw):
        time, flags, size, id, _ = unpack_from("diiii", raw, offset)
        offset += 24
        mesg = unpack_from("%ss" % (size - 1), raw, offset)[0]
        offset += size
        time = ceil((time - 25569.0) * 86400) - 7200
        yield time, mesg

class TlenArchivesFoundCaseTable(FlagFramework.CaseTable):
    """ Found Tlen archives table class. """
    # primary= "inode_id"
    name = 'tlen_archives'
    columns = [
      [InodeIDType, {}],
      [StringType, {"name":"Path", "column":"path"}],
      [LongStringType, {"name":"Chat", "column":"chat"}],
      [TimestampType, {"name":"timestamp", "column":"timestamp"}],
    ]


class TlenFinder(Reports.report):
    """ A report class for finding Tlen archive files """
    name = "Show found Tlen Archives"
    family = "Log Finder"
    description="The report returns a table of known Gadu Gadu archive files."

    def form(self,query,result):
        result.case_selector()
        
    def display(self,query,result):
        dbh=self.DBO(query['case'])
        try:
            result.table(
                elements = [ 
                             FilenameType(case=query['case']),
                             TimestampType(name='Timestamp', column='timestamp'),
                             LongStringType(name='Chat', column='chat'),
                             ],
                table = 'tlen_archives',
                case = query['case']
                )
        except DB.DBError,e:
            result.para("Error reading the Type table.")
            result.para("Error reported was:")
            result.text(e,style="red")


class TlenArchiveScan(GenScanFactory):
    """ Scan filesystem for Tlen Archives """
    default = True
    depends = ['TypeScan']
    group = "FileScanners"
    order=400

    class Scan(BaseScanner):

        def process(self, data,metadata=None):
            dbh=DB.DBO(self.case)


        def finish(self):
            dbh=DB.DBO(self.case)

            template = "INSERT INTO tlen_archives(inode_id, path, chat, timestamp) values (%s, '%s', '%s', '%s')"
            if self.fd.__class__.__name__ == "MountedFS_file":
                try:
                    for time, chat in iterate_tlen_chats(self.fd.fd.name):
                        sql = template % (self.inode_id, self.fd.fd.name, chat, time)
                        dbh.execute(sql)
                except StructError:
                    pass


if __name__ == "__main__":
    with open(sys.argv[1]) as f:
        raw = f.read()
        for t in get_lines(raw):
            print t
